package demon1;

import demon1.IMyArrayList;

import java.util.Arrays;

public class MyArrayList implements IMyArrayList {
    public int[] array;
    public int useSize;
    public MyArrayList(){
        this.array=new int[10];
    }
    public boolean isFull(){
        if(useSize==0){
            return true;
        }else {
            return false;
        }
    }
    public void Expansion(){
        this.array= Arrays.copyOf(array,2*array.length);
    }
    public void checkPos(int pos)throws PosNotLegalException {
        if(pos<0||pos>useSize){
            throw new PosNotLegalException("pos位置不合法");
        }
    }
    @Override
    public void add(int data) {
        if(isFull()){
            Expansion();
        }
        this.array[useSize]=data;
        this.useSize++;

    }

    @Override
    public void add(int pos, int data) {
        if(isFull()){
            Expansion();
        }
        try{
            checkPos(pos);
        }catch (PosNotLegalException e){
            e.printStackTrace();
        }
        for(int i=useSize-1;i>=pos;i--){
            this.array[i+1]=this.array[i];
        }
        this.useSize++;
        array[pos]=data;
    }

    @Override
    public boolean contains(int toFind) {
        for (int i = 0; i < array.length; i++) {
            if(array[i]==toFind){
                return true;
            }
        }
        return false;
    }

    @Override
    public int indexOf(int toFind) {
        for(int i=0;i<array.length;i++){
            if(array[i]==toFind){
                return i;
            }
        }
        return -1;
    }

    @Override
    public int get(int pos) {
        try{
            checkPos(pos);
        }catch(PosNotLegalException e){
            e.printStackTrace();
        }
        return array[pos];
    }

    @Override
    public void set(int pos, int value) {
        try {
            checkPos(pos);
        }catch (PosNotLegalException e){
            e.printStackTrace();
        }
        if(isFull()){
            Expansion();
        }
        array[pos]=value;
    }

    @Override
    public void remove(int toRemove) {
        int pos=indexOf(toRemove);
        if(pos==-1){
            return;
        }
        for (int i = pos; i <useSize-1 ; i++) {
            array[i]=array[i+1];
        }
        useSize--;
    }

    @Override
    public int size() {
        return useSize;
    }

    @Override
    public void clear() {
        useSize=0;
    }

    @Override
    public void display() {
        for (int i = 0; i < useSize; i++) {
            System.out.println(array[i]);
        }
    }
}
